<template>
  <div class="timeline-page">
    <!-- 使用公共页面头部组件 -->
    <PageHeader
      title="时间轴"
      :itemCount="timelineItems.length"
      itemUnit="篇文章"
      :secondaryCount="availableYears.length"
      secondaryUnit="个年份的记录"
    />

    <!-- 年份选择器 -->
    <YearTabs
      :availableYears="availableYears"
      :selectedYear="selectedYear"
      @update:selectedYear="selectYear"
    />

    <!-- 时间轴内容 -->
    <div class="timeline-wrapper">
      <!-- 加载状态 -->
      <LoadingState v-if="loading" />

      <!-- 年份内容组 -->
      <YearSection
        v-else-if="displayYears.length > 0"
        v-for="year in displayYears"
        :key="year"
        :year="year"
        :timelineItems="timelineItems"
      />

      <!-- 无内容状态 -->
      <EmptyState v-else :selectedYear="selectedYear" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import PageHeader from '@/components/PageHeader.vue'
import YearTabs from './components/YearTabs.vue'
import YearSection from './components/YearSection.vue'
import LoadingState from './components/LoadingState.vue'
import EmptyState from './components/EmptyState.vue'
import { getArticleTimeline } from '@/api/article'
import { getCategoryColor } from '@/utils/colorUtils'

// 文章数据
const timelineItems = ref([])
const loading = ref(true)

// 数据转换函数：将后端数据转换为前端需要的格式
const transformTimelineData = (apiData) => {
  return apiData.map((item) => ({
    id: item.id,
    date: item.createOn, // 使用创建时间作为日期
    category: item.category?.name || '默认分类',
    categoryColor: getCategoryColor(item.category?.name || '默认分类'),
    title: item.title,
    description: item.description || '暂无描述',
    link: `/article/${item.id}`,
    // 保留原始数据用于其他用途
    originalData: item,
  }))
}

// 获取时间轴数据
const fetchTimelineData = async () => {
  try {
    loading.value = true
    const data = await getArticleTimeline()
    timelineItems.value = transformTimelineData(data)
  } catch (error) {
    console.error('获取时间轴数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 筛选状态
const selectedYear = ref(null) // null 表示显示所有年份

// 获取所有可用年份并排序
const availableYears = computed(() => {
  const years = [...new Set(timelineItems.value.map((item) => new Date(item.date).getFullYear()))]
  return years.sort((a, b) => b - a) // 降序排列
})

// 计算当前要显示的年份列表
const displayYears = computed(() => {
  if (selectedYear.value === null) {
    return availableYears.value
  }
  return [selectedYear.value]
})

// 选择年份
const selectYear = (year) => {
  selectedYear.value = year
}

// 添加滚动监听功能
const yearSections = ref([])
let observer = null

onMounted(() => {
  // 获取时间轴数据
  fetchTimelineData()

  // 初始化年份元素引用
  setTimeout(() => {
    yearSections.value = Array.from(document.querySelectorAll('.year-section'))

    // 创建 Intersection Observer 实例
    observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          // 当年份区域进入视口
          if (entry.isIntersecting) {
            entry.target.classList.add('active')

            // 提取年份值添加到 URL hash (可选)
            // const year = entry.target.getAttribute('data-year')
            // if (year && window.history.replaceState) {
            //   window.history.replaceState(null, null, `#${year}`)
            // }
          } else {
            entry.target.classList.remove('active')
          }
        })
      },
      {
        threshold: 0.2, // 当20%的元素可见时触发
        rootMargin: '-100px 0px -100px 0px', // 视口边缘偏移量
      },
    )

    // 观察每个年份区域
    yearSections.value.forEach((section) => {
      if (section) {
        observer.observe(section)
      }
    })
  }, 100) // 延迟一点执行，确保DOM已完全渲染
})

onUnmounted(() => {
  // 清理 observer
  if (observer) {
    yearSections.value.forEach((section) => {
      observer.unobserve(section)
    })
  }
})

defineOptions({ name: 'TimelinePage' })
</script>

<style lang="scss" scoped>
.timeline-page {
  padding: 2rem 1rem 4rem;
  max-width: 860px;
  margin: 0 auto;

  // 时间轴内容包装器
  .timeline-wrapper {
    position: relative;
  }
}

// 响应式调整
@media (max-width: 768px) {
  .timeline-page {
    padding: 1rem 0 2.5rem;
  }
}

// 适配安全区域为移动设备提供更好的体验
@supports (padding-bottom: env(safe-area-inset-bottom)) {
  @media (max-width: 768px) {
    .timeline-page {
      padding-bottom: calc(2.5rem + env(safe-area-inset-bottom));
    }
  }
}
</style>
